package com.situ.stl.controller;

import com.situ.stl.constants.Constants;
import com.situ.stl.entity.Course;
import com.situ.stl.entity.Member;
import com.situ.stl.service.CourseService;
import com.situ.stl.util.Result;
import com.situ.stl.vo.CourseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/course")
@Slf4j
public class CourseController {
    @Autowired
    private CourseService courseService;


    @GetMapping
    public Result getAll(Integer page, Integer limit, Course course) {
        if (ObjectUtils.isEmpty(page) && ObjectUtils.isEmpty(limit)) {
            List<CourseVo> courseList = courseService.select(course);
            return Result.success(Constants.STATUS_200, courseList);
        }
        return Result.success(Constants.STATUS_200, courseService.searchByPage(page, limit, course));
    }
    @PutMapping
    public Result modifyMember(@RequestBody Course course) {
        try {
            int row = courseService.modifyCourse(course);
            if (row == 0) {
                return Result.error(Constants.EDIT_Member_ERROR, "修改课程失败");
            }

        } catch (Exception e) {
            log.info("修改失败");
            return Result.success(Constants.STATUS_10001, e.getMessage());
        }
        return Result.success(Constants.STATUS_200);
    }
    @DeleteMapping("/{id}")
    public Result deleteCourse(@PathVariable Integer id) throws Exception {
        try {
            int row = courseService.deleteCourse(id);
            if(row == 0) {
                return Result.error(Constants.STATUS_10001, "删除课程失败");
            }
        } catch (Exception e) {
            log.info("删除失败");
            return Result.success(Constants.STATUS_10001, e.getMessage());
        }
        return Result.success(Constants.STATUS_200);


    }
    @PostMapping
    public Result add(@RequestBody Course course) {

        try {
            int row = courseService.addCourse(course);
            if (row == 0) {
                return Result.error(Constants.EDIT_Member_ERROR, "添加课程失败");
            }
        } catch (Exception e) {
            log.info("添加失败");
            return Result.success(Constants.STATUS_10001, e.getMessage());
        }
        return Result.success(Constants.STATUS_200);

    }
}
